package com.king.modules.monitor.controller;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.king.common.annotation.Log;
import com.king.common.constant.Constants;
import com.king.common.enums.BusinessType;
import com.king.common.exception.job.TaskException;
import com.king.common.utils.poi.ExcelUtil;
import com.king.common.utils.quartz.CronUtils;
import com.king.common.utils.quartz.ScheduleUtils;
import com.king.common.utils.text.StringUtils;
import com.king.framework.base.controller.YyBaseController;
import com.king.framework.base.domain.vo.AjaxResult;
import com.king.modules.monitor.domain.SysJobEntity;
import com.king.modules.monitor.service.SysJobService;

/**
 * 调度任务信息操作处理
 * 
 * @author king
 */
@RestController
@RequestMapping("/monitor/job")
public class SysJobController extends YyBaseController<SysJobEntity> {
	@Autowired
	private SysJobService jobService;


	/**
	 * 导出定时任务列表
	 */
	@PreAuthorize("@sps.hasAuthority('monitor:job:export')")
	@Log(title = "定时任务", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, SysJobEntity sysJob) {
		List<SysJobEntity> list = jobService.selectJobList(sysJob);
		ExcelUtil<SysJobEntity> util = new ExcelUtil<SysJobEntity>(SysJobEntity.class);
		util.exportExcel(response, list, "定时任务");
	}


	/**
	 * 新增定时任务
	 */
	@PreAuthorize("@sps.hasAuthority('monitor:job:add')")
	@Log(title = "定时任务", businessType = BusinessType.INSERT)
	@PostMapping("/addJob")
	public AjaxResult addJob(@RequestBody SysJobEntity job) throws SchedulerException, TaskException {
		if (!CronUtils.isValid(job.getCronExpression())) {
			return error("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
		} else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
			return error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
		} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(),
				new String[] { Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS })) {
			return error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
		} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(),
				new String[] { Constants.HTTP, Constants.HTTPS })) {
			return error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
		} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
			return error("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
		} else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
			return error("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
		}
		job.setCr(getUserId());
		return toAjax(jobService.insertJob(job));
	}

	/**
	 * 修改定时任务
	 */
	@PreAuthorize("@sps.hasAuthority('monitor:job:edit')")
	@Log(title = "定时任务", businessType = BusinessType.UPDATE)
	@PostMapping("/updateJob")
	public AjaxResult updateJob(@RequestBody SysJobEntity job) throws SchedulerException, TaskException {
		if (!CronUtils.isValid(job.getCronExpression())) {
			return error("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
		} else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
			return error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
		} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(),
				new String[] { Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS })) {
			return error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
		} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(),
				new String[] { Constants.HTTP, Constants.HTTPS })) {
			return error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
		} else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
			return error("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
		} else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
			return error("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
		}
		job.setMr(getUserId());
		return toAjax(jobService.updateJob(job));
	}

	/**
	 * 定时任务状态修改
	 */
	@PreAuthorize("@sps.hasAuthority('monitor:job:changeStatus')")
	@Log(title = "定时任务", businessType = BusinessType.UPDATE)
	@PostMapping("/changeStatus")
	public AjaxResult changeStatus(@RequestBody SysJobEntity job) throws SchedulerException {
		SysJobEntity newJob = jobService.selectJobById(job.getId());
		newJob.setStatus(job.getStatus());
		return toAjax(jobService.changeStatus(newJob));
	}

	/**
	 * 定时任务立即执行一次
	 */
	@PreAuthorize("@sps.hasAuthority('monitor:job:changeStatus')")
	@Log(title = "定时任务", businessType = BusinessType.UPDATE)
	@PostMapping("/run")
	public AjaxResult run(@RequestBody SysJobEntity job) throws SchedulerException {
		boolean result = jobService.run(job);
		return result ? success() : error("任务不存在或已过期！");
	}
}
